import 'package:flutter/material.dart';
import 'package:logger/logger.dart';
import 'package:mongo_dart/mongo_dart.dart';

class MongoService {
  late Db db;
  final String collectionName = 'test';
  final String operationLogCollectionName = 'operation_log';
  final Logger _logger = Logger();
  bool _isConnected = false;

  bool get isConnected => _isConnected;

  String cleanObjectId(dynamic id) {
    if (id is String) {
      if (id.startsWith('ObjectId("') && id.endsWith('")')) {
        return id.substring(10, id.length - 2);
      }
      return id;
    } else if (id is ObjectId) {
      return id.oid;
    }
    return id.toString();
  }

  Future<void> connect(
    String connectionString, [
    VoidCallback? onConnected,
  ]) async {
    if (_isConnected) {
      _logger.i('数据库已连接，无需重复连接');
      onConnected?.call();
      return;
    }
    try {
      db = Db(connectionString);
      await db.open();
      _isConnected = true;
      _logger.i('数据库连接成功');
      onConnected?.call();
    } catch (e) {
      _isConnected = false;
      _logger.e('数据库连接失败: $e');
      throw Exception('连接失败：$e');
    }
  }

  Future<void> close() async {
    if (!_isConnected) {
      _logger.i('数据库已断开，无需重复断开');
      return;
    }
    try {
      await db.close();
      _isConnected = false;
      _logger.i('数据库连接关闭');
    } catch (e) {
      _logger.e('关闭数据库失败: $e');
      throw Exception('断开连接失败：$e');
    }
  }

  Future<List<Map<String, dynamic>>> getProjects() async {
    try {
      final collection = db.collection(collectionName);
      return await collection.find().toList();
    } catch (e) {
      _logger.e('获取项目失败: $e');
      throw Exception('获取项目失败：$e');
    }
  }
}
